package com.ycg.vue.utils;

import com.github.pagehelper.util.StringUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description 获取ip地址
 * @Author jink
 * @Date 2024/6/6
 */
public class IpAddressUtils {

    public static String getIpAddress(HttpServletRequest request) {
    
        String Xip = request.getHeader("X-Real-IP");
        
        String XFor = request.getHeader("X-Forwarded-For");
        
        //多次反向代理后会有多个ip值，第一个ip才是真实ip
        if(!StringUtil.isEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
        
            int index = XFor.indexOf(",");
            
            if(index != -1){
            
                return XFor.substring(0,index);
            }else {
            
                return XFor;
            }
        }
        
        XFor = Xip;
        
        if(!StringUtil.isEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor))
            return XFor;
            
        if (!StringUtil.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor))
            XFor = request.getHeader("Proxy-Client-IP");
            
        if (!StringUtil.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor))
            XFor = request.getHeader("WL-Proxy-Client-IP");
            
        if (!StringUtil.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor))
            XFor = request.getHeader("HTTP_CLIENT_IP");
            
        if (!StringUtil.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor))
            XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
            
        if (!StringUtil.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor))
            XFor = request.getRemoteAddr();
            
        return XFor;
    }
}